<!-- 收银台 -->
<template>
  <s-layout title="收银台">
    <view class="bg-white ss-modal-box ss-flex-col">
      <view class="modal-header ss-flex-col ss-col-center ss-row-center">
        <view class="money-box ss-m-b-20">
          <text class="money-text">{{ state.totalAmount }}</text>
        </view>
        <view class="time-text">
          <text>{{ payDescText }}</text>
        </view>
      </view>
      <view class="modal-content ss-flex-1">
        <view class="pay-title ss-p-l-30 ss-m-y-30">选择支付方式</view>
        <radio-group @change="onTapPay">
          <label
            class="pay-type-item"
            v-for="item in state.payMethods"
            :key="item.title"
          >
            <view
              class="pay-item ss-flex ss-col-center ss-row-between ss-p-x-30 border-bottom"
              :class="{ 'disabled-pay-item': item.disabled }"
              v-if="allowedPayment.includes(item.value)"
            >
              <view class="ss-flex ss-col-center">
                <image
                  class="pay-icon"
                  v-if="item.disabled"
                  :src="sheep.$url.cdn('/static/img/shop/pay/cod_disabled.png')"
                  mode="aspectFit"
                >
                </image>
                <image
                  class="pay-icon"
                  v-else
                  :src="sheep.$url.cdn(item.icon)"
                  mode="aspectFit"
                >
                </image>
                <text class="pay-title">{{ item.title }}</text>
              </view>
              <view class="check-box ss-flex ss-col-center ss-p-l-10">
                <view
                  class="userInfo-money ss-m-r-10"
                  v-if="item.value == 'money'"
                >
                  余额: {{ userInfo.price }}元
                </view>
                <view
                  class="userInfo-money ss-m-r-10"
                  v-if="item.value == 'offline' && item.disabled"
                >
                  部分商品不支持
                </view>
                <radio
                  :value="item.value"
                  color="var(--ui-BG-Main)"
                  style="transform: scale(0.8)"
                  :disabled="item.disabled"
                  :checked="state.payment === item.value"
                />
              </view>
            </view>
          </label>
        </radio-group>
      </view>
      <view class="scroll-box" v-if="cardList.length > 0">
        <view style="margin-left: 30rpx; margin-bottom: 20rpx">购物卡 </view>
        <scroll-view scroll-x class="index-nav-scroll">
          <radio-group>
            <view
              :class="[
                'index-nav-view',
                item.cardType == 1 ? 'index-nav-view1' : 'index-nav-view2',
              ]"
              v-for="(item, index) in cardList"
              :key="index"
            >
              <view
                :class="['index', item.cardType == 1 ? 'index1' : 'index2']"
                @click="clearPaymentSelection(item, index)"
              >
                <view> {{ item.cardType != 1 ? "电影卡" : "蛋糕卡" }} </view>
                <view style="margin-top: 10rpx; font-size: 26rpx">
                  余额：{{ item.remainingAmount }}元
                </view>
                <view class="indexradio"
                  ><radio
                    :checked="selectedCard == index"
                    color="var(--ui-BG-Main)"
                  /> </view
              ></view>
            </view>
          </radio-group>
        </scroll-view>
      </view>

      <!-- 工具 -->
      <view
        class="modal-footer ss-flex ss-row-center ss-col-center ss-m-t-80 ss-m-b-40"
      >
        <button
          v-if="state.payStatus === 0"
          class="ss-reset-button past-due-btn"
        >
          检测支付环境中
        </button>
        <button
          v-else-if="state.payStatus === -1"
          class="ss-reset-button past-due-btn"
          disabled
        >
          支付已过期
        </button>
        <button
          v-else
          class="ss-reset-button save-btn"
          @tap="onPay"
          :disabled="state.payStatus !== 1"
          :class="{ 'disabled-btn': state.payStatus !== 1 }"
        >
          立即支付
        </button>
      </view>
    </view>
  </s-layout>
</template>
<script setup>
import { computed, reactive, ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import { Base64 } from "js-base64";

const userInfo = computed(() => sheep.$store("user").userInfo);

// 检测支付环境
const state = reactive({
  orderType: "goods",
  payment: "wechat",
  totalAmount: "",
  orderInfo: {},
  payStatus: 0, // 0=检测支付环境, -2=未查询到支付单信息， -1=支付已过期， 1=待支付，2=订单已支付
  payMethods: ["wechat", "money","mixed"],
  payId: "",
  goToPay: false,
  productId: 0,
  orderSN: 0,
});

onShow(() => {
  if (state.goToPay) {
    // 根据订单类型跳转到不同页面
    if (state.orderInfo && state.orderInfo.orderType === '4') {
      // 点餐订单,跳转到餐厅订单列表
      const cateringOrder = state.orderInfo.cateringOrder || {};
      const brandOt = state.orderInfo.brandOt || 1; // 默认肯德基
      const brandName = state.orderInfo.brandName || '肯德基';
      
      sheep.$router.redirect("/pages/catering/order-list", {
        ot: brandOt,
        cateringName: brandName
      });
    } else {
      // 其他订单,跳转到通用订单列表
      sheep.$router.redirect("/pages/order/list");
    }
  }
});
const allowedPayment = computed(() => {
  if (state.orderType === "recharge") {
    return sheep.$store("app").platform.recharge_payment;
  }
  return sheep.$store("app").platform.payment;
});

const payMethods = [
  {
    icon: "https://picture-1326598115.cos.ap-nanjing.myqcloud.com/miniFont/d6700c8ae26b43c2bcb7a902b0282977.png",
    title: "微信支付",
    value: "wechat",
    disabled: false,
  },
  {
    icon: "https://picture-1326598115.cos.ap-nanjing.myqcloud.com/miniFont/3e2607e35b5f4c668e79dd2b211e1bba.png",
    title: "余额支付",
    value: "money",
    disabled: false,
  },
  {
    icon: "https://picture-1326598115.cos.ap-nanjing.myqcloud.com/miniFont/d6700c8ae26b43c2bcb7a902b0282977.png",
    title: "混合支付",
    value: "mixed",
    disabled: false,
  },
];

// getPayableCard
const cardList = ref([]);
const cardNumber = ref();
const typeArray = ref("3,1");

const getPayableCard = async () => {
  // 确保 typeArray.value 是一个数组
  const data = await sheep.$api.order.getPayableCard(
    {},
    { type: typeArray.value }
  );
  cardList.value = data.data;
  cardNumber.value = data.data[0].cardNumber;
  console.log(cardList.value, "我的值");
};
// getPayableCard();

const onPay = () => {
  console.log("orderInfo", state.orderInfo);
  if (state.payment === "") {
    sheep.$helper.toast("请选择支付方式");
    return;
  }

  if (state.payment === "wechat") {
    uni.showModal({
      title: "提示",
      content: "确定要支付吗?",
      success: function (res) {
        if (res.confirm) {
          state.goToPay = true;

          // #ifdef MP-WEIXIN
          // 微信小程序支付
          sheep.$api.pay
            .miniPay({
              payId: state.orderSN,
              wechatType: 1, // 小程序支付类型
            })
            .then((res) => {
              let params = res.data;
              console.log(params, "小程序支付参数");
              params.package = "prepay_id=" + params.package_;
              uni.requestPayment({
                provider: "wxpay",
                nonceStr: params.nonceStr,
                package: params.package,
                paySign: params.paySign,
                signType: params.signType,
                timeStamp: params.timeStamp.toString(),
                success: (res) => {
                  console.log(res);
                  uni.showToast({
                    title: "支付成功！",
                    duration: 2000,
                  });
                  
                  // 根据订单类型跳转
                  if (state.orderInfo && state.orderInfo.orderType === '4') {
                    // 点餐订单,跳转到餐厅订单列表
                    const brandOt = state.orderInfo.brandOt || 1;
                    const brandName = state.orderInfo.brandName || '肯德基';
                    
                    uni.reLaunch({
                      url: `/pages/catering/order-list?ot=${brandOt}&cateringName=${encodeURIComponent(brandName)}`,
                    });
                  } else {
                    // 其他订单,跳转到通用订单列表
                    uni.reLaunch({
                      url: "/pages/order/list",
                    });
                  }
                },
                fail: (err) => {
                  if (err.errMsg === "requestPayment:fail cancel") {
                    sheep.$helper.toast("支付已手动取消");
                  } else {
                    console.log("小程序支付失败:", err);
                  }
                },
              });
            })
            .catch((err) => {
              console.log("获取支付参数失败:", err);
              state.goToPay = false;
            });
          // #endif

          // #ifdef APP-PLUS
          // APP端微信支付
          sheep.$api.pay
            .miniPay({
              payId: state.orderSN,
              wechatType: 1, // APP支付类型
            })
            .then((res) => {
              let params = res.data;
              console.log("params参数", params);

              // APP端微信支付参数格式
              const orderInfo = {
                // appid: params.appid,
                appid: `wx4a2bffdc375ec538`,
                noncestr: params.nonceStr,
                // packageValue: params.package_,
                packageValue: "Sign=WXPay",
                // partnerid: params.partnerid,
                partnerid: 1704318073,
                prepayid: params.tradeNo,
                timestamp: params.timeStamp,
                sign:"a0bb1606846812513fa24b58e878a0a2",
              };

              console.log("APP微信支付参数", orderInfo);

              uni.requestPayment({
                provider: "wxpay",
                orderInfo: orderInfo,
                success: (res) => {
                  console.log("APP微信支付成功:", res);
                  uni.showToast({
                    title: "支付成功！",
                    duration: 2000,
                  });
                  uni.reLaunch({
                    url: "/pages/order/list",
                  });
                },
                fail: (err) => {
                  if (err.errMsg === "requestPayment:fail cancel") {
                    sheep.$helper.toast("支付已手动取消");
                  } else {
                    console.log("APP微信支付失败:", err);
                    uni.showToast({
                      title: "支付失败，请重试",
                      icon: "none",
                    });
                  }
                  state.goToPay = false;
                },
              });
            })
            .catch((err) => {
              console.log("获取APP支付参数失败:", err);
              uni.showToast({
                title: "获取支付参数失败APP",
                icon: "none",
              });
              state.goToPay = false;
            });
          // #endif;
        }
      },
    });
  } else if (state.payment === "money") {
    if (state.totalAmount - userInfo.price < 0) {
      uni.showToast({
        icon: "none",
        title: "余额不足，请选择其他支付方式",
      });
      return;
    }
    uni.showModal({
      title: "提示",
      content: "确定要余额支付吗?",
      success: function (res) {
        if (res.confirm) {
          state.goToPay = true;
          sheep.$api.pay
            .miniPay({
              payId: state.orderSN,
              wechatType: 2,
            })
            .then((res) => {
              if (res.code === 200) {
                sheep.$store("user").getInfo();
                uni.showToast({
                  title: "支付成功！",
                  duration: 2000,
                });
                uni.reLaunch({
                  url: "/pages/order/list",
                });
              }
            });
        }
      },
    });
  } else if (state.payment === "mixed") {
    uni.showModal({
      title: "提示",
      content: "确定要混合支付吗?",
      success: function (res) {
        if (res.confirm) {
          state.goToPay = true;
          sheep.$api.pay
            .miniPay({
              payId: state.orderSN,
              wechatType: 3,
            })
            .then((res) => {
              if (res.code === 200) {
                // 混合支付成功后，直接调用微信支付
                let params = res.data;
                console.log('混合支付后端返回参数:', params);
                
                // #ifdef MP-WEIXIN
                // 微信小程序支付
                params.package = "prepay_id=" + params.package_;
                console.log('小程序混合支付参数:', params);
                uni.requestPayment({
                  provider: "wxpay",
                  nonceStr: params.nonceStr,
                  package: params.package,
                  paySign: params.paySign,
                  signType: params.signType,
                  timeStamp: params.timeStamp.toString(),
                  success: (res) => {
                    console.log('混合支付=>微信支付结果',res);
                    uni.showToast({
                      title: "支付成功！",
                      duration: 2000,
                    });
                    uni.reLaunch({
                      url: "/pages/order/list",
                    });
                  },
                  fail: (err) => {
                    if (err.errMsg === "requestPayment:fail cancel") {
                      sheep.$helper.toast("支付已手动取消");
                    } else {
                      console.log('小程序混合支付失败:', err);
                      uni.showToast({
                        title: "支付失败: " + (err.errMsg || "未知错误"),
                        icon: "none",
                        duration: 3000,
                      });
                    }
                    state.goToPay = false;
                  },
                });
                // #endif
                
                // #ifdef APP-PLUS
                // APP端微信支付 - 需要后端返回APP端专用的支付参数
                console.log('APP混合支付，需要特殊处理');
                uni.showToast({
                  title: "APP端混合支付暂不支持",
                  icon: "none",
                  duration: 3000,
                });
                state.goToPay = false;
                // #endif
              } else {
                console.log('混合支付接口返回错误:', res);
                uni.showToast({
                  title: res.msg || "获取支付参数失败",
                  icon: "none",
                  duration: 3000,
                });
                state.goToPay = false;
              }
            })
            .catch((err) => {
              console.log("混合支付接口调用失败:", err);
              uni.showToast({
                title: "获取支付参数失败，请重试",
                icon: "none",
                duration: 3000,
              });
              state.goToPay = false;
            });
        }
      },
    });
  } else if (state.payment === "card") {
    uni.showModal({
      title: "提示",
      content: "确定要充值卡支付吗?",
      success: function (res) {
        if (res.confirm) {
          state.goToPay = true;
          sheep.$api.pay
            .miniPay({
              payId: state.orderSN,
              wechatType: 4,
              cardNumber: cardNumber.value,
            })
            .then((res) => {
              if (res.code === 200) {
                sheep.$store("user").getInfo();
                uni.showToast({
                  title: "支付成功！",
                  duration: 2000,
                });
                uni.reLaunch({
                  url: "/pages/order/list",
                });
              }
            });
        }
      },
    });
  }
};

const payDescText = computed(() => {
  return "";
});

function checkPayStatus() {
  if (state.orderInfo.status === "unpaid") {
    state.payStatus = 1;
    return;
  }
  if (state.orderInfo.status === "closed") {
    state.payStatus = -1;
    return;
  }
  state.payStatus = 2;
}

function onTapPay(e) {
  state.payment = e.detail.value;
  selectedCard.value = null;
}

async function setRechargeOrder(id) {
  const { data, error } = await sheep.$api.trade.order(id);
  if (error === 0) {
    state.orderInfo = data;
    state.payMethods = payMethods;
    checkPayStatus();
  } else {
    state.payStatus = -2;
  }
}

async function setGoodsOrder(id) {
  state.payStatus = 1;

  console.log(
    payMethods,
    payMethods.filter((it) => it.value === "wechat")
  );

  state.payMethods = payMethods.filter(
    (it) =>
      it.value === "wechat" || it.value === "money" || it.value === "mixed"
  );
}

onLoad(async (options) => {
  const authInfo = sheep.$store("app").authInfo;
  console.log("Allowed Payment Methods:", allowedPayment.value);
  if (!sheep.$store("user").userInfo.openId && authInfo) {
    await sheep.$api.user.setWechatInfo(
      Base64.encode(JSON.stringify(authInfo))
    );
    sheep.$store("user").userInfo.openId = authInfo.openid;
  }
  let id = "";
  if (options.orderSN) {
    id = options.orderSN;
    state.orderSN = options.orderSN;
  }
  if (options.id) {
    id = options.id;
  }
  if (options.totalAmount) {
    state.totalAmount = options.totalAmount;
  }
  if (options.productId) {
    state.productId = options.productId;
  }
  
  // 保存品牌信息用于支付成功后跳转
  if (options.brandOt) {
    state.orderInfo.brandOt = parseInt(options.brandOt);
  }
  if (options.brandName) {
    state.orderInfo.brandName = decodeURIComponent(options.brandName);
  }
  // 保存订单类型
  if (options.type === 'goods') {
    state.orderInfo.orderType = '4'; // 点餐订单
  }
  state.payId = id;
  if (options.type === "recharge") {
    state.orderType = "recharge";
    // 充值订单
    setRechargeOrder(id);
  } else {
    state.orderType = "goods";
    // 商品订单
    setGoodsOrder(id);
  }
});

const selectedCard = ref();

const clearPaymentSelection = (item, index) => {
  console.log(index);
  selectedCard.value = index;
  cardNumber.value = item.cardNumber;
  console.log(cardNumber.value, "selectedCard");
  state.payment = null;
  state.payment = "card"; // 将选中状态设置为 null，取消选中
};
</script>

<style lang="scss" scoped>
.pay-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 26rpx;
}

.ss-modal-box {
  // max-height: 1000rpx;

  .modal-header {
    position: relative;
    padding: 60rpx 20rpx 40rpx;

    .money-text {
      color: $red;
      font-size: 46rpx;
      font-weight: bold;
      font-family: OPPOSANS;

      &::before {
        content: "￥";
        font-size: 30rpx;
      }
    }

    .time-text {
      font-size: 26rpx;
      color: $gray-b;
    }

    .close-icon {
      position: absolute;
      top: 10rpx;
      right: 20rpx;
      font-size: 46rpx;
      opacity: 0.2;
    }
  }

  .modal-content {
    overflow-y: auto;

    .pay-title {
      font-size: 26rpx;
      font-weight: 500;
      color: #333333;
    }

    .pay-tip {
      font-size: 26rpx;
      color: #bbbbbb;
    }

    .pay-item {
      height: 86rpx;
    }

    .disabled-pay-item {
      .pay-title {
        color: #999999;
      }
    }

    .userInfo-money {
      font-size: 26rpx;
      color: #bbbbbb;
      line-height: normal;
    }
  }

  .save-btn {
    width: 710rpx;
    height: 80rpx;
    border-radius: 40rpx;
    background: linear-gradient(
      90deg,
      var(--ui-BG-Main),
      var(--ui-BG-Main-gradient)
    );
    color: $white;
  }

  .disabled-btn {
    background: #e5e5e5;
    color: #999999;
  }

  .past-due-btn {
    width: 710rpx;
    height: 80rpx;
    border-radius: 40rpx;
    background-color: #999;
    color: #fff;
  }
}
.scroll-box {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  margin-top: 40rpx;
}
.index-nav-scroll {
  width: 100%;
}
/* 公共样式 */
.index-nav-view {
  display: inline-block;
  margin: 0rpx 22rpx;
  width: 70%;
  height: 200rpx;
  box-sizing: border-box;
  border-radius: 20rpx;
  padding: 10rpx;
}

.index {
  height: 100%;
  border-radius: 20rpx;
  box-sizing: border-box;
  font-size: 32rpx;
  padding: 10rpx;
  font-weight: 700;
  position: relative;
}

.indexradio {
  position: absolute;
  right: 0rpx;
  bottom: 10rpx;
}

/* 特定样式 */
.index-nav-view1 {
  background: linear-gradient(to right, #ffc39e, #ff8273);
}
.index1 {
  background: linear-gradient(to right, #ffdcbd, #ff9f99);
  color: #fd9744;
}

.index-nav-view2 {
  background: linear-gradient(to right, #454756, #333243);
}

.index2 {
  background: linear-gradient(to right, #4a4b56, #373541);
  border: #c8b17c solid 2rpx;
  color: #c8b17c;
}

.index-nav-view3 {
  background: linear-gradient(to right, #c181f0, #974eeb);
}

.index3 {
  background: linear-gradient(to right, #deb6fd, #8338ee);
  color: #8324b7;
}
</style>
